package com.lanxin.zc.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.Page;
import com.lanxin.bx.entity.BxInformaldetail;
import com.lanxin.bx.entity.BxInformaltype;
import com.lanxin.bx.vo.AllinformalVo;
import com.lanxin.hr.entity.JcBasicdatavalue;
import com.lanxin.hr.entity.ZzAccount;
import com.lanxin.hr.entity.ZzEmployee;
import com.lanxin.hr.service.IJcBasicdatavalueService;
import com.lanxin.hr.service.IZzEmployeeService;
import com.lanxin.zc.entity.ZcAsset;
import com.lanxin.zc.entity.ZcAssetmovelog;
import com.lanxin.zc.entity.ZcAssettype;
import com.lanxin.zc.service.IZcAssetService;
import com.lanxin.zc.service.IZcAssetmovelogService;
import com.lanxin.zc.service.IZcAssettypeService;
import com.lanxin.zc.vo.ZcassetVo;
import com.lanxin.zc.vo.ZcassetmovelogVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeParseException;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2025-07-16
 */
@Controller
@RequestMapping("/zc-asset")
public class ZcAssetController {

    @Autowired
    IZcAssetService zcAssetService;
    @Autowired
    IZcAssettypeService zcAssettypeService;
    @Autowired
    IZzEmployeeService zzEmployeeService;
    @Autowired
    IJcBasicdatavalueService jcBasicdatavalueService;
    @Autowired
    IZcAssetmovelogService zzAssetmovelogService;

    @RequestMapping("/tozcassetlist")
    public ModelAndView tozcassetlist(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            @RequestParam(value = "assetCode", required = false) String assetCode,
            @RequestParam(value = "assetNumber", required = false) String assetNumber,
            @RequestParam(value = "assetName", required = false) String assetName,
            @RequestParam(value = "type", required = false) String type,
            @RequestParam(value = "keeper", required = false) String keeper,
            @RequestParam(value = "status", required = false) String status) {

        // 调用服务层获取分页数据
        Page<ZcassetVo> zcassetVoPage = zcAssetService.selectzcassetList(page,pageSize,assetCode,assetNumber,assetName,type,keeper,status);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("zc/zcasset/zcassetlist");

       List<ZcAssettype> zcAssettypeList= zcAssettypeService.list();

        QueryWrapper<ZzEmployee> zcEmployeeQueryWrapper = new QueryWrapper<>();
        zcEmployeeQueryWrapper.eq("oid", keeper);
        ZzEmployee zcEmployee = zzEmployeeService.getOne(zcEmployeeQueryWrapper);
        // 添加分页数据到视图
        modelAndView.addObject("zcEmployee", zcEmployee);
        modelAndView.addObject("zcAssettypeList", zcAssettypeList);
        modelAndView.addObject("zcassetVoPage", zcassetVoPage);
        modelAndView.addObject("assetCode", assetCode);
        modelAndView.addObject("assetNumber", assetNumber);
        modelAndView.addObject("assetName", assetName);
        modelAndView.addObject("type", type);
        modelAndView.addObject("keeper", keeper);
        modelAndView.addObject("status", status);

        // 添加分页信息（可选）
        modelAndView.addObject("total", zcassetVoPage.getTotal());
        modelAndView.addObject("pageNum", zcassetVoPage.getPageNum());
        modelAndView.addObject("pageSize", zcassetVoPage.getPageSize());
        modelAndView.addObject("pages", zcassetVoPage.getPages()); // 总页数

        return modelAndView;
    }


    @RequestMapping("/assetInfo")
    public ModelAndView assetInfo(@RequestParam(value = "oid", required = false) String oid){

        ModelAndView modelAndView = new ModelAndView();
        QueryWrapper<ZcAsset> zcAssetQueryWrapper = new QueryWrapper<>();
        zcAssetQueryWrapper.eq("oid", oid);
        ZcAsset zcAsset = zcAssetService.getOne(zcAssetQueryWrapper);
        modelAndView.addObject("zcAsset", zcAsset);
        // 转换LocalDate为Date
        if(zcAsset.getProduceTime() != null) {
            Date produceDate = Date.from(zcAsset.getProduceTime().atStartOfDay(ZoneId.systemDefault()).toInstant());
            modelAndView.addObject("produceDate", produceDate);
        }

        if(zcAsset.getRegDate() != null) {
            Date regDate = Date.from(zcAsset.getRegDate().atStartOfDay(ZoneId.systemDefault()).toInstant());
            modelAndView.addObject("regDate", regDate);
        }
        // 转换LocalDateTime为Date
        if(zcAsset.getCreateDate() != null) {
            Date createDate = Date.from(zcAsset.getCreateDate().atZone(ZoneId.systemDefault()).toInstant());
            modelAndView.addObject("createDate", createDate);
        }
        // 获取库管信息（假设有zcEmployeeService）
        ZzEmployee zcEmployee = zzEmployeeService.getById(zcAsset.getKeeper());
        modelAndView.addObject("zcEmployee", zcEmployee);

        // 获取经办人信息（假设有zcEmployeeService）
        ZzEmployee zcJinban = zzEmployeeService.getById(zcAsset.getJinban());
        modelAndView.addObject("zcJinban", zcJinban);

        QueryWrapper<ZcAssettype> zcAssettypeQueryWrapper = new QueryWrapper<>();
        zcAssettypeQueryWrapper.eq("oid", zcAsset.getType());
        ZcAssettype zcAssettype=zcAssettypeService.getOne(zcAssettypeQueryWrapper);

        QueryWrapper<JcBasicdatavalue> jcBasicdatavalueQueryWrapper = new QueryWrapper<>();
        jcBasicdatavalueQueryWrapper.eq("oid", zcAsset.getDepositary());
        JcBasicdatavalue jcBasicdatavalue1=jcBasicdatavalueService.getOne(jcBasicdatavalueQueryWrapper);


        //获取商品来源
        JcBasicdatavalue jcBasicdatavalue= jcBasicdatavalueService.getById(zcAsset.getAddType());
        modelAndView.addObject("jcBasicdatavalue", jcBasicdatavalue);
        modelAndView.addObject("jcBasicdatavalue1", jcBasicdatavalue1);
        modelAndView.addObject("zcAssettype", zcAssettype);
        modelAndView.setViewName("zc/zcasset/zcassetinfo");
        return modelAndView;
    }

    @RequestMapping("/deleteAsset")
    @ResponseBody
    @Transactional
    public boolean deleteAsset(@RequestParam Integer oid){
        /*bxInformaldetailService*/
        QueryWrapper<ZcAsset> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("oid",oid);
        ZcAsset zcAsset= zcAssetService.getOne(queryWrapper);
        if("N".equals(zcAsset.getStatus())||"Y".equals(zcAsset.getStatus())){
            return zcAssetService.removeById(oid);
        }
        return false;

    }

    @RequestMapping("/editAssetState")
    @ResponseBody
    @Transactional
    public boolean editAssetState(@RequestParam Integer oid,
                                  @RequestParam String status){
        QueryWrapper<ZcAsset> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("oid",oid);
        ZcAsset zcAsset=zcAssetService.getOne(queryWrapper);
        zcAsset.setStatus(status);
        return zcAssetService.updateById(zcAsset);

    }

    @RequestMapping("/listAssetmovelog")
    public ModelAndView listAssetmovelog(@RequestParam(value = "assetid", required = false) String assetid){

        ModelAndView modelAndView = new ModelAndView();

        List<ZcassetmovelogVo> zcAssetmovelogs= zzAssetmovelogService.selectlogbyassetid(assetid);
        modelAndView.addObject("zcAssetmovelogs",zcAssetmovelogs);
        modelAndView.setViewName("zc/zcasset/zcassetmovelog");
        return modelAndView;
    }

    @RequestMapping("/toAddAsset")
    public ModelAndView toAddAsset(Integer oid){
        ModelAndView modelAndView = new ModelAndView();
       QueryWrapper<JcBasicdatavalue> queryWrapper = new QueryWrapper<>();
       queryWrapper.eq("type",2);
       List<JcBasicdatavalue> jcBasicdatavalue1=jcBasicdatavalueService.list(queryWrapper);

       QueryWrapper<JcBasicdatavalue> queryWrapper1 = new QueryWrapper<>();
       queryWrapper1.eq("type",4);
       List<JcBasicdatavalue> jcBasicdatavalue2=jcBasicdatavalueService.list(queryWrapper1);

       List<ZcAssettype> zcAssettype= zcAssettypeService.list();

       ZcAsset zcAsset;

        if (oid != null) {
            zcAsset = zcAssetService.getById(oid);
            QueryWrapper<ZzEmployee> zcEmployeeQueryWrapper = new QueryWrapper<>();
            zcEmployeeQueryWrapper.eq("oid", zcAsset.getKeeper());
            ZzEmployee zzEmployee= zzEmployeeService.getOne(zcEmployeeQueryWrapper);
            modelAndView.addObject("zzEmployee", zzEmployee);
        } else {
            zcAsset = new ZcAsset();
        }


        modelAndView.addObject("jcBasicdatavalue1",jcBasicdatavalue1);
        modelAndView.addObject("jcBasicdatavalue2",jcBasicdatavalue2);
        modelAndView.addObject("zcAssettype",zcAssettype);
        modelAndView.addObject("zcAsset",zcAsset);
        modelAndView.setViewName("zc/zcasset/zcassetedit");
        return modelAndView;
    }


    @RequestMapping("/editAsset")
    public String editAsset(
            @RequestParam(value = "oid", required = false) Integer oid,
            @RequestParam(value = "type", required = false) Integer type,
            @RequestParam(value = "assetCode", required = false) String assetCode,
            @RequestParam(value = "assetNumber", required = false) String assetNumber,
            @RequestParam(value = "assetName", required = false) String assetName,
            @RequestParam(value = "guige", required = false) String guige,
            @RequestParam(value = "produceTime", required = false) String produceTimeStr,
            @RequestParam(value = "depositary", required = false) Integer depositary,
            @RequestParam(value = "keeper", required = false) Integer keeper,
            @RequestParam(value = "price", required = false) String priceStr,
            @RequestParam(value = "regDate", required = false) String regDateStr,
            @RequestParam(value = "addType", required = false) Integer addType,
            @RequestParam(value = "remark", required = false) String remark,
            @RequestParam(value = "amount", required = false) Integer amount,
            @RequestParam(value = "status", required = false) String status,
            HttpSession session) {

        // 1. 创建实体对象
        ZcAsset zcAsset = new ZcAsset();
        if (oid != null) {
            zcAsset = zcAssetService.getById(oid); // 编辑时先查询原数据
            if (zcAsset == null) {
                return "redirect:/zc-asset/toAddAsset"; // 防止ID不存在
            }
        }

        // 2. 手动绑定非日期字段（避免对象绑定失败）
        zcAsset.setType(type);
        zcAsset.setAssetCode(assetCode);
        zcAsset.setAssetNumber(assetNumber);
        zcAsset.setAssetName(assetName);
        zcAsset.setGuige(guige);
        zcAsset.setDepositary(depositary);
        zcAsset.setKeeper(keeper);
        zcAsset.setAddType(addType);
        zcAsset.setRemark(remark);
        zcAsset.setAmount(amount);
        zcAsset.setStatus(status);

        // 3. 处理价格（String -> BigDecimal，避免格式错误）
        if (priceStr != null && !priceStr.isEmpty()) {
            try {
                zcAsset.setPrice(new BigDecimal(priceStr));
            } catch (Exception e) {
                zcAsset.setPrice(null); // 价格格式错误时设为空（或根据业务处理）
            }
        }

        // 4. 处理日期字段（手动转换，彻底规避格式问题）
        try {
            if (produceTimeStr != null && !produceTimeStr.isEmpty()) {
                zcAsset.setProduceTime(LocalDate.parse(produceTimeStr));
            }
            if (regDateStr != null && !regDateStr.isEmpty()) {
                zcAsset.setRegDate(LocalDate.parse(regDateStr));
            }
        } catch (Exception e) {
            // 日期格式错误时不修改原日期（或根据业务处理）
        }

        // 5. 新增时设置创建时间和经办人
        if (oid == null) {
            zcAsset.setCreateDate(LocalDateTime.now());
            ZzAccount myaccount = (ZzAccount) session.getAttribute("myaccount");
            if (myaccount != null) {
                zcAsset.setJinban(myaccount.getAid());
            }
        }

        // 6. 保存或更新
        if (oid != null) {
            zcAssetService.updateById(zcAsset);
        } else {
            zcAssetService.save(zcAsset);
        }

        return "redirect:/zc-asset/tozcassetlist";
    }


    @RequestMapping("/checkAssetCode")
    @ResponseBody
    public Map<String, Boolean> checkAssetCode(String assetCode, Integer oid) {
        QueryWrapper<ZcAsset> wrapper = new QueryWrapper<>();
        wrapper.eq("assetCode", assetCode);
        if (oid != null) {
            wrapper.ne("oid", oid);
        }
        long count = zcAssetService.count(wrapper);

        // 构造JSON对象（包含valid字段）
        Map<String, Boolean> result = new HashMap<>();
        result.put("valid", count == 0);
        return result;
    }

}
